    /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package location.general;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import system.general.Exc;
import system.general.Logged;
import system.general.Message;
import system.general.Persistencia;

/**
 *
 * @author emojica
 */
@ManagedBean(name = "location_country")
@RequestScoped
public class Main extends Beans {

    Logged logged;
    private Persistencia persistencia = new Persistencia();
    private Message msg = new Message();
    private Find location_countryFind = new Find();
    private List<Beans> location_countryList = new ArrayList<>();
    private String sql;
    private Map<String, String> map = new LinkedHashMap<>();

    public Main() {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        logged = (Logged) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "logged");
        load();
    }

    private void load() {
        try {
            sql = "SELECT * FROM public.v_localizacion_pais "
                    + "WHERE id =" + logged.getMasterId();
            ResultSet rsts = persistencia.executeRsts(sql);
            while (rsts.next()) {
                setId(rsts.getInt("id"));
                setNombre(rsts.getString("nombre"));
            }
        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void insert() {
        try {

            //se carga el mapa con los valores
            map.clear();
            map.put("lower(nombre) = '" + getNombre().toLowerCase() + "'", " ");

            //Verifica si el registro existe, de lo contrario lo inserta
            if (location_countryFind.byExist(map)) {
                throw new Exc("m5");
            }

            sql = "INSERT INTO public.localizacion_pais (nombre) "
                    + "VALUES ('" + getNombre() + "')";

            //Inserta la información del registro
            persistencia.executeUpdate(sql);

            //Localiza el id del registro recien insertado, con la llave única
            location_countryList = location_countryFind.byMap(map);

            //Asigna el id del registro insertado a la variable global
            logged.setMasterId(location_countryList.get(0).getId());
            logged.setMasterName(getNombre());

            throw new Exc("m1");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public Integer insert(String nombre) throws Exc, SQLException, Exception {
        map.clear();
        map.put("lower(nombre) = '" + nombre.toLowerCase() + "'", " ");

        //Verifica si el registro existe, de lo contrario lo inserta
        if (location_countryFind.byExist(map)) {
            throw new Exc("m5");
        }

        sql = "INSERT INTO public.localizacion_pais (nombre) "
                + "VALUES ('" + nombre + "')";

        //Inserta la información del registro
        persistencia.executeUpdate(sql);

        location_countryList = location_countryFind.byMap(map);
        return location_countryList.get(0).getId();
    }

    public void update() {
        try {

            //Verifica si hay registros seleccionados
            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }

            //carga el mapa con valores
            map.clear();
            map.put("id <> " + logged.getMasterId(), " AND ");
            map.put("lower(nombre) = '" + getNombre().toLowerCase() + "'", " ");

            //Verifica si el registro existe, de lo contrario lo inserta
            if (location_countryFind.byExist(map)) {
                throw new Exc("m5");
            }

            sql = "UPDATE public.localizacion_pais SET " + "nombre = '" + getNombre() + "' " + "WHERE id =" + logged.getMasterId();

            //Actualiza la información del registro
            persistencia.executeUpdate(sql);

            logged.setMasterName(getNombre());

            throw new Exc("m2");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void delete() {
        try {

            //Verifica si hay registros seleccionados
            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }

            //Elimina el resgistro por el id_persona
            deleteById(logged.getMasterId());
            clear();

            throw new Exc("m3");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void deleteById(int id) throws Exc, SQLException, Exception {
        sql = "DELETE FROM public.localizacion_pais "
                + "WHERE id = " + id;
        persistencia.executeUpdate(sql);
    }

    public void clear() {
        logged.clearRecord();
        clearBeans();
    }

    public void selectedRecordId(int tempId) {
        logged.setDetailId(tempId);
        load();
    }

    private String namePackage() {
        Package pack = this.getClass().getPackage();
        return pack.getName();
    }
}
